package com.dk.recite.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dk.recite.entity.Vistor;
import com.dk.recite.entity.Word;
//import com.dk.recite.service.WordService;
import com.dk.recite.mapper.VistorMapper;
import com.dk.recite.mapper.WordMapper;
import com.dk.recite.service.WordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

@RestController
public class MainController {

    @Autowired
    private WordService wordService;

    @Autowired
    private VistorMapper mapper;

    @GetMapping("/test")
    public String test() {
        return "success";
    }

    @GetMapping("/initial/{useKey}")
    public String initial(@PathVariable("useKey")String useKey) throws IOException {
        wordService.init(useKey);
        return "success";
    }

    @GetMapping("/init/{useKey}")
    public String init(@PathVariable("useKey")String useKey) throws IOException {
        QueryWrapper<Word> wrapper = new QueryWrapper<>();
        wrapper.eq("use_key",useKey);
        List<Word> list = wordService.list(wrapper);
        for(Word d : list) {
            d.setStatus(0);
        }
        wordService.updateBatchById(list);
        return "success";
    }

    /**
     * 获取词典里单词
     * @param page
     * @param useKey 用户key
     * @param firstLetter 首字母
     * @return
     */
    @GetMapping("/listAll")
    public Page<Word> listAll(Page page,String useKey,String firstLetter,Integer status) {
        if(StringUtils.checkValNull(useKey)) return new Page<>();
        Vistor vistor = new Vistor();
        vistor.setUseKey(useKey);
        vistor.setVistDate(new Date());
        mapper.insert(vistor);
        QueryWrapper<Word> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.checkValNotNull(useKey),"use_key",useKey)
                .eq(StringUtils.checkValNotNull(firstLetter),"first_letter",firstLetter.toLowerCase())
                .eq(StringUtils.checkValNotNull(status),"status",status);
        return wordService.page(page,wrapper);
    }


    @PostMapping("/alterWordStatus/{id}/{status}")
    public void updateStatus(@PathVariable Long id,@PathVariable Integer status) {
        Word word = wordService.getById(id);
        if(word != null && status != null && status >= 0 && status <= 2) {
            word.setStatus(status);
            wordService.updateById(word);
        }
    }

}
